package com.block.risk.service.type;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.block.common.service.LogFactory;
import com.block.db.entity.MemberExtInfo;
import com.block.db.entity.RiskBaseInfo;
import com.block.db.entity.RiskResultInfo;
import com.block.db.mapper.RiskResultInfoMapper;
import com.block.risk.constant.RiskConstant;
import com.block.risk.factory.DefaultItemFactory;
import com.block.risk.model.param.RiskControlParam;
import com.block.risk.model.result.RiskControlResult;
import com.block.risk.model.result.RiskJudgeResult;
import com.block.risk.service.IRiskResultInfoService;
import com.block.risk.service.IRiskService;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;

@Service
public class DefaultRiskService implements IRiskService {

    private static Logger log = LogFactory.getRiskLog();

    @Autowired
    IRiskResultInfoService riskResultInfoService;
    @Resource
    RiskResultInfoMapper riskResultInfoMapper;

    @Override
    public RiskControlResult riskHandlerExec(RiskControlParam riskParamInfo) {

        MemberExtInfo memberExtInfo = riskParamInfo.getMemberExtInfo();

        RiskControlResult controlResult = new RiskControlResult();
        controlResult.setSuccess(false);

        RiskResultInfo riskResultInfo =  riskResultInfoMapper.getEntityByDataIdAndTypeAndUid(riskParamInfo.getDataId(), riskParamInfo.getDataType(), memberExtInfo.getUid());
        if (ObjectUtil.isEmpty(riskResultInfo)){
            // 查到结果
            riskResultInfo  = this.queryQuanJingResult(memberExtInfo, riskParamInfo);
            if (ObjectUtil.isEmpty(riskResultInfo)){
                controlResult.setMessage("风控结果为空");
                return controlResult;
            }
        }

        if (!ObjectUtil.equals(Integer.valueOf(1), riskResultInfo.getStatus())){
            controlResult.setMessage(riskResultInfo.getMessage());
            return controlResult;
        }

        controlResult.setSuccess(true);
        controlResult.setMessage("风控通过");
        return controlResult;
    }

    private RiskResultInfo queryQuanJingResult(MemberExtInfo memberExtInfo, RiskControlParam riskParamInfo){

        RiskBaseInfo riskBaseInfo = new RiskBaseInfo();
        riskBaseInfo.setDataId(Integer.valueOf(RiskConstant.DEFAULT_DATA_ID));
        riskBaseInfo.setDataType(RiskConstant.DEFAULT_DATA_TYPE);
        riskBaseInfo.setConfigId(Integer.valueOf(RiskConstant.DEFAULT_DATA_CONFIGID));

        RiskResultInfo commonRiskResultInfo = riskResultInfoService.getCommonRiskResult(memberExtInfo, riskBaseInfo);
        // 查询该数据的结果
        if (ObjectUtil.isEmpty(commonRiskResultInfo)){
            return null;
        }

        RiskResultInfo riskResultInfo = new RiskResultInfo();
        riskResultInfo.setConfigId(commonRiskResultInfo.getConfigId());
        riskResultInfo.setDataId(riskParamInfo.getDataId());
        riskResultInfo.setDataType(riskParamInfo.getDataType());
        riskResultInfo.setDateInfo(LocalDate.now().toString());
        riskResultInfo.setChargeFlag(RiskConstant.CHARGE_TYPE_FREE);

        riskResultInfo.setUid(commonRiskResultInfo.getUid());
        riskResultInfo.setUsername(commonRiskResultInfo.getUsername());
        riskResultInfo.setMobile(commonRiskResultInfo.getMobile());
        riskResultInfo.setIdcard(commonRiskResultInfo.getIdcard());
        riskResultInfo.setCode(commonRiskResultInfo.getCode());
        riskResultInfo.setResult(commonRiskResultInfo.getResult());
        riskResultInfo.setResultInfo(commonRiskResultInfo.getResultInfo());

        // 风控结果判断
        RiskJudgeResult riskJudgeResult = this.riskControlResultInfo(commonRiskResultInfo, riskParamInfo.getDataId(), riskParamInfo.getDataType());
        riskResultInfo.setStatus(riskJudgeResult.isPass()?1:0);
        riskResultInfo.setMessage(riskJudgeResult.getResult());

        boolean save = riskResultInfoService.save(riskResultInfo);
        if (!save){
            return null;
        }
        return riskResultInfo;
    }

    private RiskJudgeResult riskControlResultInfo(RiskResultInfo riskResultInfo, String dataId, String dataType){
        RiskJudgeResult riskJudgeResult = new RiskJudgeResult();
        riskJudgeResult.setPass(false);

        if (!StrUtil.equals(riskResultInfo.getCode(), "0")){
            riskJudgeResult.setResult(riskResultInfo.getMessage());
            return riskJudgeResult;
        }

        String resultInfo = riskResultInfo.getResult();
        try {
            JSONObject jsonObject = JSON.parseObject(resultInfo);

            String code = jsonObject.getString("code");
            String desc = jsonObject.getString("desc");
            if (!StrUtil.equals(code, "0")){
                riskJudgeResult.setResult(desc);
                return riskJudgeResult;
            }

            JSONObject result_detail = jsonObject.getJSONObject("result_detail");
            if (ObjectUtil.isEmpty(result_detail)){
                riskJudgeResult.setResult("result_detail对象为空");
                return riskJudgeResult;
            }

            String type = StrUtil.format("{}_{}", dataId, dataType);
            RiskJudgeResult controlResult = DefaultItemFactory.getService(type).getControlResult(result_detail);
            log.info("【type】{}【controlResult】{}", type, JSON.toJSONString(controlResult));
            return controlResult;
        }catch (JSONException exception){
            riskJudgeResult.setResult(riskResultInfo.getResult());
        }
        return riskJudgeResult;
    }

}
